package org.example;

public class LinkList {
    Node head = null;
    static class Node{
        Node next = null;  //节点的地址，首先是空的
        int data;  //节点的对象，即存储的数据

        public Node(int data){
            this.data = data;
        }
    }
    // 接下来实现在链表中插入数据
    public void insert(int data){
        Node newNode = new Node(data);
        if(head == null){
            head = newNode;
            return ;
        }
        Node tmp = head;
        while(tmp.next != null){
            tmp = tmp.next;
        }
        tmp.next = newNode;
    }

    // 实现删除指定位置节点
    public boolean delete(int data){
        if(data < 1 || data >length()){
            return false;
        }
        if (data == 1) {
            head = head.next;
            return true;
        }
        int i = 1;
        Node preNode = head;
        Node curNode = preNode.next;
        while(curNode != null){
            if(i == data){
                preNode.next = curNode.next;
                return true;
            }
            preNode = curNode;
            curNode = curNode.next;
            i++;
        }
        return false;
    }

    //返回节点长度
    public int length(){
        int length = 0;
        Node tmp = head;
        while(tmp != null){
            length++;
            tmp = tmp.next;
        }
        return length;
    }

    //打印
    public void printList(){
        Node tmp = head;
        while(tmp != null){
            System.out.print(tmp.data + " ");
            tmp = tmp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkList list = new LinkList();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        list.insert(5);
        list.printList();
        list.delete(3);
        list.printList();
        System.out.println(list.length());
    }
}
